package parser.conector;


import java.io.IOException;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class Http {
	
	public Http(){
		httpclient.getParams().setParameter("http.protocol.handle-redirects", false);
	}
	
	private HttpClient httpclient = new DefaultHttpClient();
	private ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
	    public byte[] handleResponse(
	            HttpResponse response) throws ClientProtocolException, IOException {
	    	HttpEntity entity = response.getEntity();
	    	if (entity != null) {
	            return EntityUtils.toByteArray(entity);
	        } else {
	            return null;
	        }
	    }
	};
	
	public void addAuthentication (String host, Integer port, String protocol, String user, String pass){
		HttpHost targetHost = new HttpHost(host, port, protocol); 

		((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(
		        new AuthScope(targetHost.getHostName(), targetHost.getPort()), 
		        new UsernamePasswordCredentials(user, pass));
	}
	
	public void randSleep()
	{
		Random r = new Random();
		try {
		Thread.sleep((long)(1000 + 2000*r.nextFloat()));
		} catch (InterruptedException ignored) {}
	}

	
	public String httpGetPage(String page){
		HttpGet httpGet = new HttpGet(page);
		try {
			byte[] response;
			response = httpclient.execute(httpGet, handler);
			return new String(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}